<?php
/**
 * Author  : zxz
 * Datetime: 2019/3/17 下午7:18
 */

namespace Xy\Rbac\Services;


use Illuminate\Support\Facades\DB;
use Xy\Rbac\Repositories\RbacRoleRepository;

class RbacRoleService {
    protected $_rbacRoleRepository;
    
    public function __construct(RbacRoleRepository $rbacRoleRepository) {
        $this->_rbacRoleRepository = $rbacRoleRepository;
    }
    
    /**
     * @param $paginateQueryModel
     * @param $conditions
     * @return mixed
     */
    public function getPage() {
        return $this->_rbacRoleRepository->getPage();
    }
    
    /**
     * @param $request
     *
     * @return mixed
     */
    public function storeRbacRole($request) {
        $dataInfo = $request->post();
        $fillAbel = array_keys($request->rules());
        
        is_null($dataInfo['desc']) && $dataInfo['desc'] = '';
        
        return $this->_rbacRoleRepository->storeRbacRole($dataInfo, $fillAbel);
    }
    
    /**
     * @param $id
     * @param $request
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     * @throws \Exception
     */
    public function updateRbacRole($id,$request) {
        $dataInfo = $request->input();
        $fillAble = $request->getRuleKeys();
        
        return $this->_rbacRoleRepository->updateRbacRoleById($id, $dataInfo, $fillAble);
    }
    
    /**
     * @param $id
     * @return array
     * @throws \Exception
     */
    public function destroyRbacRole($id) {
        $deleteItem = null;
        DB::transaction(function () use (&$deleteItem, $id) {
            $deleteItem = $this->_rbacRoleRepository->destroyPowerRbacRole($id);
            $deleteItem && $deleteItem->userRoles()->delete();
        });
        
        return $deleteItem;
    }
    
    /**
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getAllRbacRole(){
        return $this->_rbacRoleRepository->getAllRbacRole();
    }
    
    /**
     * 分配页面权限给角色
     *
     * @param $id
     * @param $request
     *
     * @return mixed
     */
    public function assignRolePowerPage($id, $request) {
        $powerFieldName = 'power';
        $power          = $request->input($powerFieldName);
        $power          = is_array($power) ? array_values($power) : [];
        
        return $this->_rbacRoleRepository->updateRbacRoleById($id, [$powerFieldName => $power], [$powerFieldName]);
    }
}